<?php
ob_start();

class db
{

    private $host;
    private $user;
    private $pw;
    private $db;
    private $charset; //设置字符集

    function __construct($config)
    {
        $this->host = $config['db_host'];
        $this->user = $config['db_user'];
        $this->pw = $config['db_pw'];
        $this->db = $config['db_name'];
        $this->charset = $config['db_charset'];
        $this->conn = $this->conn();
    }

    function conn()
    {
        $link = mysqli_connect($this->host, $this->user, $this->pw, $this->db) or die(mysqli_connect_error());
        mysqli_query($link, "SET NAMES '$this->charset'");
        return $link;
    }

    /**
     * 插入方法
     * @param array $data
     * @param string $table
     * @return id
     */
    function insert($table, $data)
    {
        $names = implode(',', array_keys($data));
        $values = "'" . implode("','", array_values($data)) . "'";
        $res = mysqli_query($this->conn, "INSERT INTO $table($names)VALUES($values)");
        if ($res) {
            return mysqli_insert_id();//取得插入的id
        } else {
            return false;
        }
    }

    /* 根据id条件来查找数据，返回一维数组
     * @param string $id
     * @param string $table
     * @return array
     */

    function foundbyId($table, $id)
    {
        $sql = mysqli_query($this->conn, "SELECT * FROM  $table where id =$id");
        $res = mysqli_fetch_array($sql);
        return $res;
    }

    /* 根据条件来查找某个字段的全部数据，返回一维数组
     * @param string $str
     * @param string $table
     * @param string $where
     * @return array
     */

    function fetchStrAll($str, $table, $where)
    {
        $sql = mysqli_query($this->conn, "SELECT $str FROM  $table where $where");
        $row = array();
        while ($res = mysqli_fetch_array($sql)) {
            $row[] = $res[$str];
        }
        return $row;
    }


    /* 根据$where条件来查找一条数据，返回一维数组
     * @param string $where
     * @param string $table
     * @return array
     */

    function foundOnebyWhere($table, $where = "")
    {
        if ($where == "") {
            $sql = mysqli_query($this->conn, "SELECT * FROM $table");
        } else {
            $sql = mysqli_query($this->conn, "SELECT * FROM $table where $where");
        }
        $res = mysqli_fetch_array($sql);
        return $res;
    }

    /*根据$where条件来查找数据,返回数量
    * @param string $where
    * @param string $table
    * @return number|boolean
    */

    function countbyWhere($table, $where = "")
    {
        if ($where == "") {
            $sql = mysqli_query($this->conn,"SELECT * FROM $table");
        } else {
            $sql = mysqli_query($this->conn,"SELECT * FROM $table where $where");
        }
        $row = mysqli_num_rows($sql);
        return $row;
    }

    /*
     *递归取得所有评论和回复
     *
     */
    function getAllReply($table, $repleyParentId, $articleId)
    {
        //第二个参数父id字段名称,默认为空(为空时默认为parentId)
        static $arr = array();
        $sql =mysqli_query($this->conn,"select * from $table where repleyParentId  =$repleyParentId and articleId=$articleId");
        while ($row = mysqli_fetch_assoc($sql)) {
            $arr[] = $row;
            $this->getAllReply($table, $row['id'], $articleId);
        }
        return $arr;
    }

    //对接收参数进行过滤
    function inject_check($sql_str)
    {
        return preg_match("#select|insert|update|delete|\'|\/\*|\*|\.\.\/|\.\  /|union|into|load_file|outfile#i", $sql_str);
    }

    //检查对应的权限
    function checkAction($r_id, $c_id, $power)
    {
        $row = $this->countbyWhere('role_columns', "r_id=$r_id and c_id=$c_id and power=$power");
        return $row;
    }

    /*
     *递归取得分类列表
     *
     */
    function getAll($table, $parentId = "", $id = 0)
    {
        //第二个参数父id字段名称,默认为空(为空时默认为parentId)
        static $arr = array();
        if ($parentId == "") {
            $sql = mysqli_query($this->conn,"select * from $table where parentId=$id");
        } else {
            $sql = mysqli_query($this->conn,"select * from $table where $parentId=$id");
        }
        while ($row = mysqli_fetch_assoc($sql)) {
            $arr[] = $row;
            $this->getAll($table, $parentId = "", $row['id']);
        }
        return $arr;
    }

    /*
    *递归取得数据
    *
    */

    function getList($table, $id = 0)
    {
        $arr = array();
        $firstData = $this->foundbyWhere($table, "parentId=$id");//查找一级子id
        foreach ($firstData as $val) {
            $childData = $this->foundbyWhere($table, "parentId='$val[id]'");
            if ($childData) {
                $arr[] = $val;
                $arr = array_merge($arr, $this->getlist($table, $val['id']));//递归查找父id等于自己的
            } else {
                $arr[] = $val;
            }
        }
        return $arr;
    }

    /*
     *递归获得子类(测试)
     *
     */
    function getChild($table, $id)
    {
        static $arr = array();//声明一次static变量后再次调用会在初始值延续
        $childData = $this->foundbyWhere('class', "parentId=$id");
        if ($childData) {
            foreach ($childData as $val) {
                $this->getChild('class', $val['id']);
            }

        }
        $arr[] = $id;
        //echo $id."<br>";

        return $arr;
    }


    /*
	*递归删除
	*
	*/
    function delAll($table, $id)
    {
        $childData = $this->foundbyWhere($table, "parentId=$id");
        if ($childData) {
            foreach ($childData as $val) {
                $this->delAll($table, $val['id']);
            }
        }
        $this->delete($table, "id=$id");
    }

    /*
    *替换空格 回车
    *
    */
    function htmlcode($content)
    {
        $content = str_replace("\n", "<br>", str_replace(" ", "&nbsp;", $content));
        return $content;
    }

    /* 根据$where条件来查找数据，返回多维数组
     * @param string $where
     * @param string $table
     * @return array
     */

    function foundbyWhere($table, $where = "")
    {
        if ($where == "") {
            $sql =mysqli_query($this->conn,"SELECT * FROM $table");
        } else {
            $sql = mysqli_query($this->conn,"SELECT * FROM $table where $where");
        }
        $row = array();
        while ($res = mysqli_fetch_array($sql)) {
            $row[] = $res;
        }
        return $row;
    }

    /* 根据$where条件来查找数据，返回数组,此方法暂时不全,不用
     * @param  $data $where
     * @param string $table
     * @return array
     */

    function foundWhere($table, $where)
    {
        foreach ($where as $key => $val) {
            $whereVal = $key . '=' . "'" . $val . "'";
            //不能直接放在where的后面，需要变量做一次赋值，不然提示错误,先进行赋值可避免引号之间的冲突
            $sql = mysqli_query($this->conn,"SELECT * FROM $table where $whereVal");
            while ($res = mysqli_fetch_array($sql)) {
                $row[] = $res; //必须把$res=mysql_fetch_array($sql)写在where里面才不会报错
            }
        }
        return $row;
    }

    /* 根据$where条件来更新数据 
     * @param string $table
     * @param array $data
     * @param string $where
     * @return number|boolean
     */

    function update($table, $data, $where)
    {
        $setsStr = "";
        foreach ($data as $key => $val) {
            $setsStr .= $key . "='" . $val . "',";
        }
        $setsStr = rtrim($setsStr, ',');
        //rtrim() 函数移除字符串右侧的空白字符或其他预定义字符(移除$setsStr最后一个逗号) 
        $res = mysqli_query($this->conn,"UPDATE $table SET $setsStr where $where");
        if ($res) {
            return mysqli_affected_rows(); //影响的行数
        } else {
            return false;
        }
    }

    /**
     * 根据$where条件来删除数据
     * @param string $table
     * @param string $where
     * @return number|boolean
     */
    function delete($table, $where)
    {
        $sql = mysqli_query($this->conn,"DELETE FROM $table where $where");
        if ($sql) {
            return mysqli_affected_rows();
        } else {
            return false;
        }
    }

}

?>

